package com.cn.dcjt.chinafree.utils

import java.math.BigDecimal
import kotlin.experimental.and

object ConvertUtils {
    private val DIGITS_LOWER = charArrayOf(
        '0', '1', '2', '3', '4', '5',
        '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    )
    private val DIGITS_UPPER = charArrayOf(
        '0', '1', '2', '3', '4', '5',
        '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
    )



    /**
     * 十六进制字符串转换为byte数组
     *
     * @param hexString
     * @return
     */
    fun hexStringToBytes(hexString: String?): ByteArray? {
        var hexString = hexString
        if (hexString == null || hexString == "") {
            return null
        }
        hexString = hexString.toUpperCase()
        val length = hexString.length / 2
        val hexChars = hexString.toCharArray()
        val d = ByteArray(length)
        for (i in 0 until length) {
            val pos = i * 2
            d[i] = (charToByte(hexChars[pos]).toInt() shl 4 or charToByte(hexChars[pos + 1]).toInt()).toByte()
        }
        return d
    }

    /**
     * char转换为byte数组
     * @param c
     * @return
     */
    fun charToByte(c: Char): Byte {
        return "0123456789ABCDEF".indexOf(c).toByte()
    }

    /**
     * 16进制转化为数字
     * @param ch 16进制
     * @param index 索引
     * @return 转化结果
     * @throws Exception 转化失败异常
     */
    private fun toDigit(ch: Char, index: Int): Int {
        val digit = Character.digit(ch, 16)
        if (digit == -1) {
            throw Exception(
                "Illegal hexadecimal character " + ch
                        + " at index " + index
            )
        }
        return digit
    }

    /**
     * bytes数组转16进制String
     * @param data bytes数组
     * @param toDigits DIGITS_LOWER或DIGITS_UPPER
     * @return 转化结果
     */
     fun bytes2Hex(data: ByteArray, toDigits: CharArray): String? {
        val l = data.size
        val out = CharArray(l shl 1)
        // two characters form the hex value.
        var i = 0
        var j = 0
        while (i < l) {
            out[j++] = toDigits[(0xF0 and data[i].toInt()) ushr 4]
            out[j++] = toDigits[0x0F and data[i].toInt()]
            i++
        }
        return String(out)
    }

    /**
     * byte数组转换为十六进制字符串
     *
     * @param b
     * @return
     */
    fun bytesToHexString(b: ByteArray): String? {
        if (b.size == 0) {
            return null
        }
        val sb = StringBuilder("")
        for (i in b.indices) {
            val value: Int = b[i].toInt() and 0xFF
            val hv = Integer.toHexString(value)
            if (hv.length < 2) {
                sb.append(0)
            }
            sb.append(hv)
        }
        return sb.toString()
    }

    /**
     * int转换为byte数组
     *
     * @param res
     * @return
     */
    fun intToByte(res: Int): ByteArray? {
        val targets = ByteArray(4)
        targets[0] = (res and 0xff).toByte() // 最低位
        targets[1] = ((res shr 8) and 0xff).toByte() // 次低位
        targets[2] = ((res shr 16) and 0xff).toByte() // 次高位
        targets[3] = (res ushr 24).toByte() // 最高位,无符号右移。
        return targets
    }

    /**
     * byte数组转换为int
     *
     * @param res
     * @return
     */
    fun byteToInt(res: ByteArray): Int {
        // 一个byte数据左移24位变成0x??000000，再右移8位变成0x00??0000
        return (res.get(3).toInt() and 0xff) or ((res.get(2).toInt() shl 8) and 0xff00) or ((res.get(1).toInt() shl 16) and 0xff0000) or ((res.get(0).toInt() shl 24) and -0x1000000)
    }


    /**
     * 保留几位小数
     */
    fun saveDecimals(cnt: Int, value: Double): Double {

        var b =  BigDecimal(value)
        return b.setScale(cnt, BigDecimal.ROUND_HALF_UP).toDouble()

    }

    /**
     * null转String
     * @param str
     * @return
     */
    fun nullOfString(str: String?): String? {
        var str = str
        if (str == null) {
            str = ""
        }
        return str
    }

    /**
     * String转Byte
     * @param str
     * @return
     */
    fun stringToByte(str: String?): Byte {
        var b: Byte = 0
        if (str != null) {
            try {
                b = str.toByte()
            } catch (e: Exception) {
            }
        }
        return b
    }

    /**
     * String转Boolean
     * @param str
     * @return
     */
    fun stringToBoolean(str: String?): Boolean {
        if (str == null) {
            return false
        } else {
            if ((str == "1")) {
                return true
            } else return if ((str == "0")) {
                false
            } else {
                try {
                    java.lang.Boolean.parseBoolean(str)
                } catch (e: Exception) {
                    false
                }
            }
        }
    }

    /**
     * String转Int
     * @param str
     * @return
     */
    fun stringToInt(str: String?): Int {
        var i = 0
        if (str != null) {
            try {
                i = str.trim { it <= ' ' }.toInt()
            } catch (e: Exception) {
                i = 0
            }
        } else {
            i = 0
        }
        return i
    }

    /**
     * String转Short
     * @param str
     * @return
     */
    fun stringToShort(str: String?): Short {
        var i: Short = 0
        if (str != null) {
            try {
                i = str.trim { it <= ' ' }.toShort()
            } catch (e: Exception) {
                i = 0
            }
        } else {
            i = 0
        }
        return i
    }

    /**
     * String转Double
     * @param str
     * @return
     */
    fun stringToDouble(str: String?): Double {
        var i = 0.0
        if (str != null) {
            try {
                i = str.trim { it <= ' ' }.toDouble()
            } catch (e: Exception) {
                i = 0.0
            }
        } else {
            i = 0.0
        }
        return i
    }

    /**
     * Int转String
     * @param i
     * @return
     */
    fun intToString(i: Int): String? {
        var str: String = ""
        try {
            str = i.toString()
        } catch (e: Exception) {
            str = ""
        }
        return str
    }

    /**
     * Double转Long
     * @param d
     * @return
     */
    fun doubleToLong(d: Double): Long {
        var lo: Long = 0
        try {
            //double转换成long前要过滤掉double类型小数点后数据
            lo = d.toString().substring(0, d.toString().lastIndexOf(".")).toLong()
        } catch (e: Exception) {
            lo = 0
        }
        return lo
    }

    /**
     * Double转Int
     * @param d
     * @return
     */
    fun doubleToInt(d: Double): Int {
        var i = 0
        try {
            //double转换成long前要过滤掉double类型小数点后数据
            i = d.toString().substring(0, d.toString().lastIndexOf(".")).toInt()
        } catch (e: Exception) {
            i = 0
        }
        return i
    }

    /**
     * Long转Double
     * @param d
     * @return
     */
    fun longToDouble(d: Long): Double {
        var lo = 0.0
        try {
            lo = d.toString().toDouble()
        } catch (e: Exception) {
            lo = 0.0
        }
        return lo
    }

    /**
     * Long转Int
     * @param d
     * @return
     */
    fun longToInt(d: Long): Int {
        var lo = 0
        try {
            lo = d.toString().toInt()
        } catch (e: Exception) {
            lo = 0
        }
        return lo
    }

    /**
     * String转Long
     * @param str
     * @return
     */
    fun stringToLong(str: String?): Long {
        var li: Long = 0
        try {
            li = java.lang.Long.valueOf((str)!!)
        } catch (e: Exception) {
            //li = new Long(0);
        }
        return li
    }

    /**
     * Long转String
     * @param li
     * @return
     */
    fun longToString(li: Long): String? {
        var str: String = ""
        try {
            str = li.toString()
        } catch (e: Exception) {
        }
        return str
    }

    fun isNumeric(number: String): Boolean {
        number.forEach {
            if (!Character.isDigit(it)) {
                return false
            }
        }
        return true
    }

}